package zjc.DeviceManage.activity;

import android.content.Intent;

import android.os.Looper;



import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import zjc.DeviceManage.R;

import zjc.DeviceManage.model.User;

import zjc.DeviceManage.service.UserService;

import zjc.DeviceManage.service.Imp.UserServiceImp;
import zjc.DeviceManage.util.MyAppliacation;


public class LoginActivity extends AppCompatActivity {

    private Button btnLogin;

    private EditText etUsername;

    private EditText etPassword;

    private User loginUser;

    private UserService userService;
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

// 获得3个UI控件对象

        etUsername=findViewById(R.id.login_username);

        etPassword=findViewById(R.id.login_password);

        btnLogin=findViewById(R.id.login_button);

// 执行按钮btnLogin的onClick事件

        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                userService = new UserServiceImp(LoginActivity.this);

                userService.loginValidate(etUsername.getText().toString(),

                        etPassword.getText().toString());

            }

        });

    }

    // 回调函数loginCallback

    public void loginCallback(User loginUser) {

        this.loginUser = loginUser;

        if (this.loginUser.getUserID() == null){

          MyAppliacation.subThreadToast("账号用户名或者密码输入错误");

        }else {

            // 将已登录成功的用户编号写入偏好文件中

           MyAppliacation.setUser_id(this.loginUser.getUserID());

            // 不能采用第一种方式在子线程中显示Toast

// MyApplication.subThreadToast("用户编号（" + this.loginUser.getUserID() + ")登录成功");

            // 必须采用第二种方式在子线程中显示Toast

            this.runOnUiThread(new Runnable() {

                public void run() {

                    Toast.makeText(LoginActivity.this,  "用户编号（"

                                    +LoginActivity.this.loginUser.getUserID() + ")登录成功",

                            Toast.LENGTH_LONG).show();

                }

            });

            Log.i("zjc","用户编号(" + this.loginUser.getUserID() + ")登录成功");

            // 跳转到MainActivity活动

            Intent intent=new Intent(LoginActivity.this,MainActivity.class);

            startActivity(intent);

            // 关闭当前LoginActivity活动

            finish();

        }

    }

}